# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import requests
import time
import hashlib
import json
import send 



time1 = int(time.time()*1000)
appkey = '34839810'



def get_fetch_data(_m_h5_tk,_m_h5_tk_enc,space_time):

    cookies = {
        '_samesite_flag_': 'true',
        'cookie2': '13c4b22465cebc407bc633bc422d094e',
        't': '3fcd03c7dc6f7884d4a9d64f544f75ce',
        '_tb_token_': 'fa670ea5eee1e',
        'cna': 'y3ArIApugT8CAavZGCMkcjZv',
        'xlly_s': '1',
        'sgcookie': 'E1000t1xbJtwy84dYVEwqT7nACKLXFFsQEFKj3aKg1jvVb38JFdlNcWYivda5Q17O5Xjm8fD44qGzkqVEyd7K8fAbJLbnOMixEZnt6GdFKAPCJE%3D',
        'tracknick': '15828546514%E8%B4%BA',
        'csg': 'b24413a4',
        'unb': '928020515',
        'isg': 'BLi40XykK73aVkc5FQEmalOWiWZKIRyrActTSfIpGvOmDVn3mjH9O9nmxQW9XdSD',
        'mtop_partitioned_detect': '1',
        '_m_h5_tk': _m_h5_tk,
        '_m_h5_tk_enc': _m_h5_tk_enc,
        'tfstk': 'g7Zta_tHK6fghziljG_nnhCELOX3DoeaS5yWmjcMlWFLF8RillmgMEFg3S0f_cqY9-NRQxfamdzUZ8tgjNoDDcoqc_flqgYaQmoXqQ2lkCuInYjmCFGsbDT7sRIRqg2aCdD1EJsujQpMhfGjcVgjA2GEHh9_GFMCpxMD1EMbGJ6KTYH6fhMXABMq3mGbGm6LdXkxZHfxOdGDDzCOybfR7epWFkHtWjKm9neUA30sNRGpc_ZKBSl7CXKXcfbd7CwLI1KzKcr8wYVGAhF8h8zjJodCwjrLdlabLCBI2JU3rVUd1nh3jXuzf0pffJnt64Za1dKaNJebr2EhFgotffamb-vRsJETsRrLnKTIXc4Kyln54CG0-8ExHo5Vv7ebUrgLDCIz-uq8rWRowxY1p9L2uVMUm5g3C5N-wPDKZOIvuEuFLvhlpTT2uVgmpbXOQE8q-Bf..',
    }

    headers = {
        'accept': 'application/json',
        'accept-language': 'zh-CN,zh;q=0.9',
        'content-type': 'application/x-www-form-urlencoded',
        'origin': 'https://www.goofish.com',
        'priority': 'u=1, i',
        'referer': 'https://www.goofish.com/',
        'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
    }
    params = {
        'jsv': '2.7.2',
        'appKey': appkey,
        't': time1,
        'sign': 'f1240f1e0d605eee56ae544ebbba9c37',
        'v': '1.0',
        'type': 'originaljson',
        'accountSite': 'xianyu',
        'dataType': 'json',
        'timeout': '20000',
        'api': 'mtop.taobao.idlemtopsearch.pc.search',
        'sessionOption': 'AutoLoginOnly',
        'spm_cnt': 'a21ybx.search.0.0',
        'spm_pre': 'a21ybx.home.categories.413.4c053da6icQK6N',
        'log_id': '4c053da6icQK6N',
    }

    data = {
        'data': '{"pageNumber":1,"keyword":"家电","fromFilter":true,"rowsPerPage":30,"sortValue":"desc","sortField":"create","customDistance":"","gps":"","propValueStr":{"searchFilter":"quickFilter:filterPersonal;"},"customGps":"","searchReqFromPage":"pcSearch","extraFilterValue":"{\\"divisionList\\":[{\\"province\\":\\"四川\\",\\"city\\":\\"成都\\"}],\\"excludeMultiPlacesSellers\\":\\"0\\",\\"extraDivision\\":\\"\\"}","userPositionJson":"{}"}',
    }

    token = _m_h5_tk
    p = token.split('_')[0] + "&" + str(time1) + "&" + appkey + "&" + data['data']
    sign=hashlib.md5(p.encode()).hexdigest()
    print(sign)
    params['sign'] = sign


    response = requests.post(
        'https://h5api.m.goofish.com/h5/mtop.taobao.idlemtopsearch.pc.search/1.0/',
        params=params,
        cookies=cookies,
        headers=headers,
        data=data,
    ).text
    #print(response)

    # 将 JSON 字符串解析为 Python 对象
    data = json.loads(response)
    

    # 提取所需字段
    result_list = data['data']['resultList']
    target_base_url = 'https://www.goofish.com/item'
    producer_list = []
    for item in result_list:
        title = item['data']['item']['main']['exContent']['detailParams']['title']
        publish_time = item['data']['item']['main']['clickParam']['args']['publishTime']
        price = item['data']['item']['main']['exContent']['detailParams']['soldPrice']  # 使用 soldPrice 代替 price
        categoryId = item['data']['item']['main']['clickParam']['args']['cCatId']
        id=item['data']['item']['main']['clickParam']['args']['id']
        spm = 'a21ybx.search.searchFeedList.1.3110389cEPoURr'
        target_url = target_base_url + '?'+ 'spm='+spm + '&' + 'id='+ id + '&' +'categoryId='+ categoryId
        picUrl = item['data']['item']['main']['exContent']['picUrl']
        

        millisecond = datetime.now().timestamp() * 1000
        # Calculate the time difference
        time_difference = millisecond - int(publish_time)

        # 将时间戳转换为 datetime 对象
        dt_object = datetime.fromtimestamp(int(publish_time)/1000)
        # 格式化 datetime 对象为字符串
        formatted_time = dt_object.strftime('%Y-%m-%d %H:%M:%S')

        #print(f" **{title}**\n   - 价格: {price}\n   - [查看详情]({formatted_time})\n")

        # Check if the time difference is less than 2 minutes
        if time_difference < space_time:
            producer_item = {
                "title": title,
                "publish_time": publish_time,
                "price": price,
                "target_url": target_url,
                "picUrl": picUrl,   
                "categoryId": categoryId,
            }
            
            producer_list.append(producer_item)          
            #print(f" **{title}**\n   - 价格: {price}\n   - [查看详情]({formatted_time})\n")
    
    print(producer_list)
    return producer_list

if __name__ == "__main__":
    # 抓取数据
    _m_h5_tk = '5aa35d483ce25b4d3a57ffe4321a912c_1739182493247'
    _m_h5_tk_enc = '0cd188b8d4cdd1ebf7882662ea9ad20b'
    # 时间间隔 :推送多长时间以前的数据MS
    space_time = 10*60*60*1000
    current_data = get_fetch_data(_m_h5_tk, _m_h5_tk_enc,space_time)
